
#include "CLogger.h"
#include <stdio.h>
#include "irrThread.h"
namespace irr
{

	CLogger::CLogger(IEventReceiver* r, io::IFileSystem* fs)
		:	LogLevel(ELL_INFORMATION), 
			Receiver(r), 
			FileSystem(fs)
	{
		//logFileName += ".//logs//";
		//logFileName += core::stringc(os::Timer::getRealTime());
		logFileName = "lastLog.log";

		if(FileSystem)
		{
			io::IWriteFile* file = this->FileSystem->createAndWriteFile(logFileName.c_str());
			if(file)
			{
				file->drop();
			}	 
		}

	}

	//! Returns the current set log level.
	ELOG_LEVEL CLogger::getLogLevel()
	{
		return LogLevel;
	}

	//! Sets a new log level.	virtual void setLogLevel(ELOG_LEVEL ll);
	void CLogger::setLogLevel(ELOG_LEVEL ll)
	{
		LogLevel = ll;
	}

	//! Prints out a text into the log
	void CLogger::log(const c8* text, ELOG_LEVEL ll)
	{
		if (ll < LogLevel)
			return;

		if(FileSystem)
		{
			io::IWriteFile* file = FileSystem->createAndWriteFile(logFileName.c_str(), true);
			core::stringc format("############");
			core::stringc logLevel;

			switch(ll)
			{
			case ELL_INFORMATION:
				{
					logLevel = "INFORMATION";
					break;
				}
			case ELL_WARNING:
				{
					logLevel = "WARNING";
					break;
				}
			case  ELL_ERROR:
				{
					logLevel = "ERROR";
					break;
				}
			case ELL_NONE:
				{
					logLevel = "NONE";
					break;
				}
			}
			
			core::stringc textStr; 
			textStr = textStr + format + logLevel + format + "\n";
			textStr = textStr + "thread\t=\t" + core::stringc(game::irrThread::getCurrentThreadId()) + "\n"; 
			textStr = textStr + "time\t=\t" + core::stringc(os::Timer::getRealTime()) + "\n"; 
			textStr = textStr + "text\t=\t" + text + "\n";

			file->write(textStr.c_str(), textStr.size());
			file->drop();
		}

		if (Receiver)
		{
			SEvent event;
			event.EventType = EET_LOG_TEXT_EVENT;
			event.LogEvent.Text = text;
			event.LogEvent.Level = ll;
			if (Receiver->OnEvent(event))
				return;
		}


		os::Printer::print(text);
	}


	//! Prints out a text into the log
	void CLogger::log(const c8* text, const c8* hint, ELOG_LEVEL ll)
	{
		if (ll < LogLevel)
			return;

		core::stringc s = text;
		s += ": ";
		s += hint;
		log (s.c_str(), ll);
	}

	//! Prints out a text into the log
	void CLogger::log(const wchar_t* text, ELOG_LEVEL ll)
	{
		if (ll < LogLevel)
			return;

		core::stringc s = text;
		log(s.c_str(), ll);
	}


	//! Prints out a text into the log
	void CLogger::log(const wchar_t* text, const wchar_t* hint, ELOG_LEVEL ll)
	{
		if (ll < LogLevel)
			return;

		core::stringc s1 = text;
		core::stringc s2 = hint;
		log(s1.c_str(), s2.c_str(), ll);
	}

	//! Sets a new event receiver
	void CLogger::setReceiver(IEventReceiver* r)
	{
		Receiver = r;
	}


} // end namespace irr